<script setup lang="ts">
defineOptions({
  name: "secure"
});
import { Message, Cellphone, Lock } from "@element-plus/icons-vue";
import {
  getUserInfoV1,
  ask_update_user_email,
  update_user_email,
  ask_update_user_phone,
  update_user_phone,
  update_user_password
} from "@/api";
import { ref, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { message } from "@/utils/message";
import { mainUrl } from "@/api/utils";
import { sendCode, sendEmailCode, Captch, CodeEmail, SetEmail, CodePhone, SetPhone } from "@/api/user";
import { getSettings } from '@/api/setting';
const percentage = ref(0);
const userInfo = ref({});
const figures = ref(0)
async function setUser() {
  percentage.value = 0
  const res = await getUserInfoV1()
  if (res.data.code == 200) {
    userInfo.value = res.data.data;
    percentage.value = 0;
  }
  ['password', 'phone', 'email'].forEach(item => {
    userInfo.value[item] && (percentage.value += 30);
  })
};
const infos = ref({})
onMounted(() => {
  setUser();
  getWidth();
  getCaptch();
  getSettings(['erweima']).then((res) => {
    infos.value = res.data.data
  });
});
//生成图形验证码
const captchaSrc = ref("");
const picode = ref("");
//生成图形验证码
const hidecode = ref();
const getCaptch = async () => {
  let { data } = await Captch({})
  hidecode.value = data.data.hcode
  captchaSrc.value = data.data.img
};
// 刷新图形验证码
const generateCaptcha = () => {
  getCaptch();
};
// 发送邮箱验证码
async function EmaillCode() {
  let res = await sendEmailCode({
    send_to: bind_email.value.email,
    email_type: "send_code",
    code: bind_email.value.picode,
    hcode: hidecode.value
  });
  if (res.data.state == 1) {
    message('发送成功！', { type: 'success' });
    sendbtn.value = true;
    const timer = setInterval(() => {
      if (countdown.value <= 0) {
        clearInterval(timer);
        sendbtn.value = false;
        countdown.value = 60;
      } else {
        countdown.value -= 1;
      }
    }, 1000);
  } else if (res.data.c_time) {
    message("发送频率过快", { type: "info" });
    sendbtn.value = true;
    countdown.value = res.data.c_time;
  } else {
    message("验证码错误", { type: "error" });
  }
}
//  发送手机验证码判定
async function PhoneCode(p0: {
  /* __placeholder__ */
  phone:
  /* __placeholder__ */
  any;
  /* __placeholder__ */
  code:
  /* __placeholder__ */
  any;
}) {
  let Phonecode = /^[1][3,4,5,7,8][0-9]{9}$/;
  if (Phonecode.test(bind_phone.value.phone)) {
    let resPhone = await sendCode({
      message_type: "send_code",
      send_to: bind_phone.value.phone,
      user_id: userInfo.value.user_id,
      code: picode.value,
      hcode: hidecode.value
    });
    if (resPhone.data.state == 1) {
      message('发送成功！', { type: 'success' });
      sendbtn.value = true;
      const timer = setInterval(() => {
        if (countdown.value <= 0) {
          clearInterval(timer);
          sendbtn.value = false;
          countdown.value = 60;
        } else {
          countdown.value -= 1;
        }
      }, 1000);
    }
  } else {
    message('请输入正确的手机号码', { type: "error" });
  }
}
//发送验证码判定
const sendbtn = ref(false);
const countdown = ref(60);
const ToSendCode = (a) => {
  if (a == 1) {
    EmaillCode()
  } else if (a == 2) {
    PhoneCode()
  }

};
const customColors = [
  // { color: "#f56c6c", percentage: 20 },
  { color: "#e6a23c", percentage: 30 },
  { color: "#5cb87a", percentage: 60 },
  { color: "#6f7ad3", percentage: 90 },
  // { color: "#6f7ad3", percentage: 100 }
];

interface PasswordBox {
  password: string;
  phone: string;
  code: string;
  re_password: string;
  new_password: string;
}

const reset_password = ref(false);
const password_box = reactive<PasswordBox>({
  password: "",
  phone: null,
  code: null,
  re_password: "",
  new_password: ""
});

// 判断新旧密码是否相同
const check_password_as = (rule: any, value: any, callback: any) => {
  if (password_box.re_password != password_box.new_password) {
    return callback(new Error("两次输入的密码不一致"));
  }
};

// 判断密码是否符合规则
const check_password_style = (rule: any, value: any, callback: any) => {
  let criteriaMatched = 0;

  // 匹配大写字母
  if (/[A-Z]/.test(password_box.new_password)) criteriaMatched++;

  // 匹配小写字母
  if (/[a-z]/.test(password_box.new_password)) criteriaMatched++;

  // 匹配数字
  if (/\d/.test(password_box.new_password)) criteriaMatched++;

  // 匹配特殊符号
  if (/[!@#$%^&*(),.?":{}|<>]/.test(password_box.new_password))
    criteriaMatched++;
  if (criteriaMatched < 2) {
    return callback(new Error("密码须含大、小写字母、数字、特殊符号至少两种"));
  }
};

// 校验邮箱
const check_email = (rule: any, value: any, callback: any) => {
  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  if (!emailPattern.test(value)) {
    return callback(new Error("邮箱格式错误"));
  }
};

const PasswordBoxRef = ref<PasswordBox>();
const password_box_rules = reactive<FormRules>({
  password: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
  phone: [
    {
      required: true,
      max: 11,
      min: 11,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  new_password: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码最应为6-20位", trigger: "change" },
    { validator: check_password_style, trigger: "change" }
  ],
  re_password: [
    { required: true, validator: check_password_as, trigger: "change" }
  ],
  email: [{ required: true, validator: check_email, trigger: "blur" }]
});
function send_update_user_password() {
  update_user_password(password_box).then(res => {
    if (res.data.code == 200) {
      message("修改成功", {
        type: "success"
      });
      reset_password.value = false;
      localStorage.removeItem("token");
      setUser()
    } else {
      message(res.data.data, {
        type: "error"
      });
    }
  });
}
const bind_phone_box = ref(false);
const bind_phone = ref({
  phone: null,
  code: null,
  ask_code: null
});
function get_ask_update_user_phone() {
  ask_update_user_phone({
    phone: bind_phone.value.phone
  }).then(res => {
    if (res.data.code == 200) {
      message("发送成功", {
        type: "success"
      });
      bind_phone.value.ask_code = res.data.data.ask_code;
    }
  });
}
// 手机校证码
const SetPhoneConde = ref(0)
async function Stephonecode() {
  let res = await CodePhone({
    phone: bind_phone.value.phone,
    code: bind_phone.value.code,
  })
  console.log(res.data.data)
  if (res.data.code == 200) {
    SetPhoneConde.value = res.data.data.ask_code;
    message("操作成功", {
      type: "success"
    })
    userInfo.value.phone = '';
    bind_phone.value.phone = '';
    picode.value = '';
    bind_phone.value.code = '';
    countdown.value = 0;
  } else {
    message(res.data.data, {
      type: "error"
    });
  }
}
// 手机号码修改请求
async function Stephoneplea(a) {
  let res = await SetPhone({
    phone: bind_phone.value.phone,
    code: bind_phone.value.code,
    ask_code: a
  })
  if (res.data.code == 200) {
    bind_phone_box.value = false;
    message(res.data.data, { type: "success" });
    bind_email.value.email = '';
    bind_email.value.picode = '';
    bind_email.value.code = '';
  } else {
    message(res.data.data, {
      type: "error"
    });
  }
}

// 手机提交判断&&手机修改提交
const submit_bind_phone = (a) => {
  if (!a && !SetPhoneConde.value) {
    update_user_phone(bind_phone.value).then(res => {
      if (res.data.code == 200) {
        message("操作成功", {
          type: "success"
        });
        bind_phone_box.value = false;
        userInfo.value.phone = 1;
        countdown.value = 0;
      } else {
        message(res.data.data, {
          type: "error"
        });
      }
    });
  } else if (a && !SetPhoneConde.value) {
    Stephonecode()
  } else if (SetPhoneConde.value) {
    Stephoneplea(SetPhoneConde.value)
  }

};
// 邮箱
const bind_email_box = ref(false);
const bindEmailRef = ref();
const bind_email = ref({
  email: null,
  code: null,
  ask_code: null,
  picode: null
});
function get_ask_update_user_email() {
  ask_update_user_email({
    email: bind_email.value.email
  }).then(res => {
    if (res.data.code == 200) {
      message("发送成功", {
        type: "success"
      });
      bind_email.value.ask_code = res.data.data.ask_code;
    }
  });
}
// 邮箱效证
const setEmailcode = ref(0)
async function setEmail() {
  let res = await CodeEmail({
    email: userInfo.value.email,
    code: bind_email.value.code
  });
  if (res.data.code == 200) {
    setEmailcode.value = res.data.data.ask_code;
    message("操作成功", {
      type: "success"
    });
    bind_email_box.value = true;
    userInfo.value.email = '';
    bind_email.value.email = '';
    bind_email.value.picode = '';
    bind_email.value.code = '';
    countdown.value = 0;
  } else {
    message('请求失败', {
      type: "error"
    });
  }

}
// 修改邮箱请求提交
async function SetEmailplea(a) {
  let res = await SetEmail({
    email: bind_email.value.email,
    code: bind_email.value.code,
    ask_code: a
  })
  if (res.data.code == 200) {
    bind_email_box.value = false;
    message(res.data.data, { type: "success" });
    bind_email.value.email = '';
    bind_email.value.picode = '';
    bind_email.value.code = '';
  } else {
    message(res.data.data, {
      type: "error"
    });
  }
}

// 邮箱提交判断&&邮箱修改提交
const submit_bind_email = (a) => {
  if (!a && !setEmailcode.value) {
    console.log(setEmailcode, a)
    update_user_email(bind_email.value).then(res => {
      if (res.data.code == 200) {
        message("操作成功", {
          type: "success"
        });
        bind_email_box.value = false;
        userInfo.value.email = 1
        countdown.value = 0;
      } else {
        message(res.data.data, {
          type: "error"
        });
      }
    });
  } else if (a && !setEmailcode.value) {
    setEmail()
  } else if (setEmailcode.value) {
    SetEmailplea(setEmailcode.value);
  }
};
const coloumNum = ref(3)
const getWidth = () => {
  let screenWidth = window.innerWidth;
  console.log('屏幕宽度:', screenWidth);
  if (screenWidth < 768) {
    coloumNum.value = 2
  }
  console.log(coloumNum.value)
}
// 取消弹窗页面还原
const initialize = () => {
  setEmailcode.value = '';
  setUser()
}
// 弹窗
const Setup = (a) => {
  if (a == 1) {
    bind_email_box.value = true
  } else {
    bind_phone_box.value = true
  }
}
// 弹窗关闭 
const close = () => {
  setEmailcode.value = '';
  bind_phone_box.value = false;
  bind_email_box.value = false;
  setUser();
} 
</script>

<template>
  <div>
    <p class='header'>
    <div class="header-icon"></div><span class="page-title">安全中心</span></p>
    <el-card style="max-width: 2000px">
      <el-descriptions title="用户信息" :column="coloumNum">
        <el-descriptions-item label="姓名">{{
          userInfo.username
        }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">
          {{ userInfo.phone }}
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">
          {{ userInfo.email || "--" }}</el-descriptions-item>
        <el-descriptions-item label="账户安全">
          <el-progress :text-inside="true" :percentage="percentage" :stroke-width="18" :color="customColors" />
        </el-descriptions-item>
        <el-descriptions-item label="实名认证">
          <el-tag v-if="userInfo.real_name_state" type="success">
            已实名</el-tag>
          <el-tag v-else><router-link to="/self/realname">未实名</router-link></el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <div class="secure_btm">
      <el-row :gutter="20">
        <el-col :xs="30" :sm="30" :md="12" :lg="12" :xl="12">
          <el-card class="secure_card secure_card_left">
            <el-card class="secure_card_card" shadow="hover">
              <el-row>
                <el-col :span="4">
                  <el-avatar :icon="Lock" />
                </el-col>
                <el-col :span="15">
                  <div class="secure_card_card_center_top">
                    <div class="secure_card_card_center_top_title">
                      登录密码 <el-tag type="success" size="small">已设置</el-tag>
                    </div>
                    <div class="secure_card_card_center_top_state">
                      安全性高的密码可以使帐号更安全,建议您定期更换密码
                    </div>
                  </div>
                </el-col>
                <el-col :span="4" style="display: flex; align-items: center">
                  <el-button type="success" round @click="reset_password = true">修改</el-button>
                </el-col>
              </el-row>
            </el-card>

            <el-card class="secure_card_card" shadow="hover">
              <el-row>
                <el-col :span="4">
                  <el-avatar :icon="Cellphone" />
                </el-col>
                <el-col :span="15">
                  <div class="secure_card_card_center_top">
                    <div class="secure_card_card_center_top_title">
                      {{ userInfo.phone ? '修改手机绑定'
                        : '手机绑定' }}
                      <el-tag :type="userInfo.phone ? 'success' : 'warning'" size="small">{{ userInfo.phone ? '已绑定'
                        : '未绑定'
                        }}</el-tag>
                    </div>
                    <div class="secure_card_card_center_top_state">
                      可用于重置密码和接受短信通知
                    </div>
                  </div>
                </el-col>
                <el-col :span="4" style="display: flex; align-items: center">
                  <el-button type="success" round @click="Setup(2)" v-if="userInfo.phone">{{
                    "修改"
                  }}</el-button>
                  <el-button type="success" round @click="Setup(2)" v-if="!userInfo.phone">{{
                    "绑定"
                  }}</el-button>
                </el-col>
              </el-row>
            </el-card>

            <el-card class="secure_card_card" shadow="hover">
              <el-row>
                <el-col :span="4">
                  <el-avatar :icon="Message" />
                </el-col>
                <el-col :span="15">
                  <div class="secure_card_card_center_top">
                    <div class="secure_card_card_center_top_title">{{ userInfo.email ? '修改邮箱绑定'
                      : '邮箱绑定'
                      }}
                      <el-tag :type="userInfo.email ? 'success' : 'warning'" size="small">{{ userInfo.email ? '已绑定'
                        : '未绑定' }}</el-tag>
                    </div>
                    <div class="secure_card_card_center_top_state">
                      可用于重置密码和接受邮件通知
                    </div>
                  </div>
                </el-col>
                <el-col :span="4" style="display: flex; align-items: center">
                  <el-button type="success" round @click="Setup(1)" v-if="userInfo.email">{{ '修改'
                    }}</el-button>
                  <el-button type="success" round @click="Setup(1)" v-if="!userInfo.email">{{
                    '绑定'
                  }}</el-button>
                </el-col>
              </el-row>
            </el-card>
          </el-card>

        </el-col>
        <el-col :xs="30" :sm="30" :md="12" :lg="12" :xl="12">
          <el-card class="secure_card secure_card_kf">
            <div>扫码联系客服</div>
            <img :src="infos.erweima" style="width:255px" />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 修改密码 -->
    <el-dialog v-model="reset_password" title="修改密码" width="500" align-center>
      <el-form ref="PasswordBoxRef" label-width="auto" :model="password_box" style="max-width: 600px"
        :rules="password_box_rules">
        <el-form-item label="旧密码" prop="password">
          <el-input v-model="password_box.password" placeholder="请输入旧密码" type="password" />
        </el-form-item>

        <el-form-item label="新密码" prop="new_password">
          <el-input v-model="password_box.new_password" placeholder="请输入新密码" type="password" />
        </el-form-item>
        <el-form-item label="再次输入新密码" prop="re_password">
          <el-input v-model="password_box.re_password" placeholder="请再次输入新密码" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reset_password = false">关闭</el-button>
          <el-button type="primary" @click="send_update_user_password">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 绑定手机号码 -->
    <el-dialog v-model="bind_phone_box" :title="userInfo.phone ? '验证原手机号码' : '绑定手机号码'" width="500" align-center
      @close=initialize>
      <el-form label-width="auto" :model="bind_phone" style="max-width: 600px" :rules="password_box_rules">
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="bind_phone.phone" placeholder="请输入手机号码" type="phone">

          </el-input>
        </el-form-item>
        <el-form-item label="图形验证码" prop="picode">
          <div class="captcha-input-container">
            <el-input v-model="picode" clearable placeholder="图形验证码" />
            <img width="100" :src="captchaSrc" alt="图形验证码" @click="generateCaptcha()" />
          </div>
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <div class="captcha-input-container">
            <el-input v-model="bind_phone.code" clearable placeholder="请输入验证码" />
            <el-button type="primary" @click="ToSendCode(2)" width="100" :disabled="sendbtn">
              {{
                sendbtn ? `重新发送(${countdown}s)` : "发送验证码"
              }}</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">关闭</el-button>
          <el-button type="primary" @click="submit_bind_phone(userInfo.phone)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 绑定邮箱 -->
    <el-dialog v-model="bind_email_box" :title="userInfo.email ? '验证原邮箱' : '绑定邮箱'" width="500" align-center
      @close=initialize>
      <el-form ref="bindEmailRef" label-width="auto" :model="bind_email" style="max-width: 600px"
        :rules="password_box_rules">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="bind_email.email" placeholder="请输入邮箱" type="phone">

          </el-input>
        </el-form-item>
        <el-form-item label="图形验证码" prop="picode">
          <div class="captcha-input-container">
            <el-input v-model="bind_email.picode" clearable placeholder="图形验证码" />
            <img width="100" :src="captchaSrc" alt="图形验证码" @click="generateCaptcha()" />
          </div>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div class="captcha-input-container">
            <el-input v-model="bind_email.code" clearable placeholder="请输入验证码" />
            <el-button type="primary" @click="ToSendCode(1)" width="100" :disabled="sendbtn">
              {{
                sendbtn ? `重新发送(${countdown}s)` : "发送验证码"
              }}</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">关闭</el-button>
          <el-button type="primary" @click.stop="submit_bind_email(userInfo.email)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.secure_card {
  margin-top: 10px;
}

.secure_card_card {
  margin-top: 10px;
}

.secure_card_card_center_top_state {
  color: #807e7e;
  font-size: 11px;
}

.secure_card_kf {
  display: flex;
  justify-content: center;
}

.secure_card_kf div {
  text-align: center;
  margin-bottom: 22px;
}

.header {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;

  .header-icon {
    height: 18px;
    width: 5px;
    background-color: #409eff;
    margin-right: 5px
  }
}

.captcha-input-container {
  display: flex;
  align-items: center;
}
</style>
